local commentsController = {}
local db = require 'models.db'
local cache = require ('library.cache'):new()
local helper = require 'library.helpers'
local vaild = require 'library.vaild'
local cookie = require 'vanilla.v.libs.cookie'

function commentsController:save()
	local post=self:getRequest():POST()

    local vaild_my=vaild:new(post);

    vaild_my:add_function('chk_pid',function(id)
    	id=helper:intval(id)
    	if id==0 then
    		return true
    	end

    	local t=db:new('comments'):where('id=?',id):count()
    	t=helper:intval(t)
    	return t>0
    end)

    vaild_my:add_function('chk_aid',function(id)
    	id=helper:intval(id)
    	if id<=0 then
    		return false
    	end

    	local c=db:new('article'):select("close_comment"):where('id=?',id):get_one()
    	if c and helper:intval(c.close_comment)>0 then
    		return true
    	end
    	return false
    end)

    vaild_my:add('pid','required|chk_pid','回复的评论不存在');
    vaild_my:add('aid','required|chk_aid','文章不存在或不允许评论');
    vaild_my:add('name','required|max_length(20)','名称需要而且不大于20个字节');
    vaild_my:add('context','required|max_length(200)','内容需要而且不大于200个字节');

    if vaild_my:run() then
    	local data={
    		name=post['name'],
    		context=post['context'],
    		ip=ngx.var.remote_addr,
    		aid=post['aid'],
    		pid=post['pid'],
    	}

    	local comments=db:new('comments')
    	local ret=comments:insert(data)
        if ret and ret['insert_id'] then
            local cookieobj=cookie:new()
            if cookieobj then
                cookieobj:set("user_name",data.name,100000)
            end
        	comments:where('pid=0 and id=?',ret['insert_id']):update({pid=ret['insert_id']})
        	return helper:show_msg(0,"保存成功",{})
        end
    end
    return helper:show_msg(1,"保存失败",vaild_my:get_errors())
end

return commentsController
